<?php
/*
* IKPHP爱客网 安装程序 @copyright (c) 2012-3000 IKPHP All Rights Reserved @author 小麦
* @Email:ikphp@sina.cn
* @小麦 关注 2014年8月9日12:11:41
*/
namespace IKPHP\Apps\Space\Models;

use IKPHP\Common\Models\BaseModel;
use IKPHP\Common\Models\User;
use IKPHP\Apps\Space\Models\UserPhotoAlbum;
use IKPHP\Common\Models\Comment;

class UserPhoto extends BaseModel {
	
	public $photoid;
	public $albumid;
	public $userid;
	
	public function getSource() {
		return IK . "user_photo";
	}
    //获取照片
    public static function getPhotos($map,$order='addtime desc',$limit=''){
		if(empty($limit)){
			$where = array (
					'conditions'=>$map,// 0 表示正常 1停用
					'order'=> $order,
			); 			
		}else{
			$where = array (
					'conditions'=>$map,// 0 表示正常 1停用
					'order'=> $order,
					'limit'=> $limit
			); 				
		}

    	$res = self::find($where); 
    	$result = array();
    	foreach($res->toArray() as $item){
    		$result[]= self::extPhoto($item);;
    	}
    	return $result;
    }
    //获取单张图片
    public static function getOnePhoto($pid){
    	$result = self::findFirst("photoid = '$pid'");
    	if($result){
    		$result = $result->toArray();
			$result = self::extPhoto($result);
    		return $result;
    	}else{
    		return false;
    	}
    }
    public static function extPhoto($result){
		$ext =  explode ( '.', $result['photoname']); 
		//图片大小
		$result['simg'] =  attach($result['photopath'].$ext[0].'_'.C('ik_simg.width').'_'.C('ik_simg.height').'.'.$ext[1]);
		$result['mimg'] =  attach($result['photopath'].$ext[0].'_'.C('ik_mimg.width').'_'.C('ik_mimg.height').'.'.$ext[1]);
		$result['bimg'] =  attach($result['photopath'].$ext[0].'_'.C('ik_bimg.width').'_'.C('ik_bimg.height').'.'.$ext[1]);
		$result['img']  =  attach($result['photopath'].$ext[0].'.'.$ext[1]);
    	return $result;    	
    }
    public function afterCreate(){
    	$album = UserPhotoAlbum::findFirst("albumid = ".$this->albumid);
    	$album->save(array('count_photo'=>$album->count_photo+1));
    }	
    public function afterDelete(){
     	$album = UserPhotoAlbum::findFirst("albumid = ".$this->albumid);
     	$count = $album->count_photo-1>0 ? $album->count_photo-1: 0;
    	$album->save(array('count_photo'=>$count));  
    	//删除评论
		$strMod = Comment::findFirst("typeid = '$this->photoid' AND type = 'UserPhoto' ");
		if($strMod){ $strMod->delete();} 	
    }
}
